package com.lfl.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import java.util.Objects;


@Component
public class RedisUtil {
    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);
    @Value("${spring.redis.url}")
    private String host;

    @Value("${spring.redis.port}")
    private Integer port;

    private static Jedis jedis;

    private static final Integer REFRESH_TIME = 60 * 10;

    private static final Integer LONG_REFRESH_TIME = 60 * 60 * 24 * 15;

    public static void setKey(String key, String value) {
        jedis.set(key, value);
    }

    public static String getStringValue(String key) {
        String value = jedis.get(key);
        return value;
    }

    public static Boolean setKeyRefresh(String key) {
        Long flag = jedis.expire(key, REFRESH_TIME);
        return flag == 1;
    }

    public static Boolean setKeyLongRefresh(String key) {
        Long flag = jedis.expire(key, LONG_REFRESH_TIME);
        return flag == 1;
    }

    public static Boolean deleteKey(String key) {
        Long flag = jedis.del(key);
        return flag == 1;
    }

    @PostConstruct
    public Jedis getJedis() {
        if (Objects.isNull(jedis)) {
            synchronized (Jedis.class) {
                if (Objects.isNull(jedis)) {
                    jedis = new Jedis(host, port);
                }
            }
        }
        return jedis;
    }
}
